package com.hanhanxiaochong.zhongxiangchuanmei.view.home.act;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hanhanxiaochong.zhongxiangchuanmei.R;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.LoginInfoBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.ShopDetailBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.ShopDetailProductBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.ShopDetailProjectBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.ShopTypeBean;
import com.hanhanxiaochong.zhongxiangchuanmei.config.page.PageRecorder;
import com.hanhanxiaochong.zhongxiangchuanmei.presenter.NearShopDetailPresenter;
import com.hanhanxiaochong.zhongxiangchuanmei.util.GlideImageLoader;
import com.hanhanxiaochong.zhongxiangchuanmei.util.ResourcesUtils;
import com.hanhanxiaochong.zhongxiangchuanmei.util.SharedPreferencesUtil;
import com.hanhanxiaochong.zhongxiangchuanmei.util.Utils;
import com.hanhanxiaochong.zhongxiangchuanmei.util.recyclerview.FullyGridLayoutManager;
import com.hanhanxiaochong.zhongxiangchuanmei.util.recyclerview.MyRecyclerView;
import com.hanhanxiaochong.zhongxiangchuanmei.view.base.BaseActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.iview.INearShopDetailView;
import com.hanhanxiaochong.zhongxiangchuanmei.view.my.act.MsgActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.shop.act.GoodDetailActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.shop.adapter.ShopNextFirstAdapter;
import com.hanhanxiaochong.zhongxiangchuanmei.view.shop.adapter.ShopProductSecondAdapter;
import com.hanhanxiaochong.zhongxiangchuanmei.view.shop.adapter.ShopProjectSecondAdapter;
import com.hanhanxiaochong.zhongxiangchuanmei.widget.StarBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.RetrofitSource;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * Author : 贾桐
 * E-mail : 653773284@qq.com
 * Time   : 2018/4/23.
 * Desc   :
 */

public class NearbyShopDetailActivity extends BaseActivity<NearShopDetailPresenter> implements INearShopDetailView {

    @BindView(R.id.img_share)
    ImageView imgShare;
    @BindView(R.id.img_favorite)
    ImageView imgFavorite;
    @BindView(R.id.good_star)
    StarBar goodStar;
    @BindView(R.id.tv_good_score)
    TextView tvGoodScore;
    @BindView(R.id.tv_good_evaluation)
    TextView tvGoodEvaluation;
    @BindView(R.id.tv_shop_project)
    TextView tvShopProject;
    @BindView(R.id.tv_shop_product)
    TextView tvShopProduct;
    @BindView(R.id.rv_first_level)
    RecyclerView rvFirstLevel;
    @BindView(R.id.rv_second_level)
    MyRecyclerView rvSecondLevel;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.iv_call)
    ImageView ivCall;
    @BindView(R.id.tv_shop_address)
    TextView tvShopAddress;
    @BindView(R.id.iv_shop_location)
    ImageView ivShopLocation;
    @BindView(R.id.shop_banner)
    Banner shopBanner;
    @BindView(R.id.scroll_shop_detail)
    ScrollView scrollShopDetail;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;

    private List<ShopTypeBean.TypeBean> firstTypeList = new ArrayList<>();
    private ShopNextFirstAdapter shopNextFirstAdapter;
    //1:项目分类；2：产品分类
    private String type = "1";
    private String phone;
    private String store_id;
    private String token;
    private String lat;
    private String lng;
    private String u_id;
    private PageRecorder pageRecorder = new PageRecorder();
    private ShopProjectSecondAdapter shopProjectSecondAdapter;
    private ShopProductSecondAdapter shopProductSecondAdapter;
    private String secondTypeId;

    public static Intent createIntent(Context context, String id) {
        Intent intent = new Intent(context, NearbyShopDetailActivity.class);
        intent.putExtra("store_id", id);
        return intent;
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_nearby_shop_detail);
    }

    @Override
    protected void initPresenter() {
        mPresenter = new NearShopDetailPresenter(this);
    }

    @Override
    protected void init() {
        initBanner();
        LoginInfoBean loginInfo = SharedPreferencesUtil.getsInstances(this).getLoginInfo();
        token = loginInfo.getToken();
        u_id = loginInfo.getU_id();
        store_id = getIntent().getStringExtra("store_id");
        mPresenter.getFirstShopType(store_id, type);
        mPresenter.getShopDetail(token, store_id);

        tvShopProject.setSelected(true);

        rvFirstLevel.setLayoutManager(new LinearLayoutManager(mContext));
        rvFirstLevel.setNestedScrollingEnabled(false);
        rvSecondLevel.setLayoutManager(new FullyGridLayoutManager(mContext, 3));
        rvSecondLevel.setHasFixedSize(true);
        rvSecondLevel.setNestedScrollingEnabled(false);
        rvSecondLevel.setCallback(() -> {
            scrollShopDetail.requestDisallowInterceptTouchEvent(true);
        });

        List<ShopTypeBean.TypeBean> list = new ArrayList<>();
        shopNextFirstAdapter = new ShopNextFirstAdapter(mContext, R.layout.item_shopnext_first,
                list);
        shopNextFirstAdapter.setmOnItemClickListener((adapter, position) -> {
            pageRecorder.moveToFirstPage();
            secondTypeId = firstTypeList.get(position).getId();
            mPresenter.getSecondShopType(type, store_id, secondTypeId, pageRecorder.getCurrentPage());
        });
        List<ShopDetailProjectBean.ProjectBean> projectBeanList = new ArrayList<>();
        List<ShopDetailProductBean> productBeanList = new ArrayList<>();
        shopProjectSecondAdapter = new ShopProjectSecondAdapter(this, R.layout.item_shopnext_second, projectBeanList);
        shopProductSecondAdapter = new ShopProductSecondAdapter(this, R.layout.item_shopnext_second, productBeanList);
        rvFirstLevel.setAdapter(shopNextFirstAdapter);
        smartRefresh.setEnableRefresh(false);
        smartRefresh.setOnLoadmoreListener(refreshlayout -> {
            mPresenter.getSecondShopType(type, store_id, secondTypeId, pageRecorder.getNextPage());
        });
    }

    private void initBanner() {
        //动态设置轮播图高度(4:3)
        ViewGroup.LayoutParams layoutParams = shopBanner.getLayoutParams();
        layoutParams.height = (int) (Utils.getScreenWidth(mContext) * 0.75);
        shopBanner.requestLayout();
        //设置banner样式
        shopBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        shopBanner.setImageLoader(new GlideImageLoader());
        //设置banner动画效果
        shopBanner.setBannerAnimation(Transformer.Default);
        //设置自动轮播，默认为true
        shopBanner.isAutoPlay(true);
        //设置轮播时间
        shopBanner.setDelayTime(3000);
        //设置指示器位置（当banner模式中有指示器时）
        shopBanner.setIndicatorGravity(BannerConfig.CENTER);
        //下标是从1开始，同时解决下标越界问题
        shopBanner.setOnBannerListener(position -> {

        });
    }

    @OnClick({R.id.ll_left, R.id.img_favorite, R.id.img_share, R.id.tv_shop_project, R.id.tv_shop_product, R.id.iv_call, R.id.iv_shop_location})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_left:
                finish();
                break;
            case R.id.img_home_msg:
                Intent intent = new Intent(mContext, MsgActivity.class);
                startActivity(intent);
                break;
            case R.id.img_favorite:
                if (imgFavorite.isSelected()) {
                    mPresenter.cancelCollectShop(token, store_id);
                } else {
                    mPresenter.collectShop(token, store_id);
                }
                break;
            case R.id.img_share:
                final String url = "http://gxcm.quan-oo.com/index/users/translate?uid=" + u_id;
                OnekeyShare oks = new OnekeyShare();
                //关闭sso授权
                oks.disableSSOWhenAuthorize();
                // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
                oks.setTitle(getString(R.string.app_name));
                // titleUrl是标题的网络链接，QQ和QQ空间等使用
                oks.setTitleUrl(url);
                // url仅在微信（包括好友和朋友圈）中使用
                oks.setUrl(url);
                oks.setShareContentCustomizeCallback((platform, paramsToShare) -> {
                    paramsToShare.setText(getString(R.string.app_name));
                    paramsToShare.setText("我分享了一个动态");
                    if (Wechat.NAME.equals(platform.getName())) {
                        paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
                        paramsToShare.setTitleUrl(url);
                        paramsToShare.setTitle(getString(R.string.app_name));
                    } else if (QQ.NAME.equals(platform.getName())) {
                        paramsToShare.setTitleUrl(url);
                        paramsToShare.setTitle(getString(R.string.app_name));
                    } else if (SinaWeibo.NAME.equals(platform.getName())) {
                        paramsToShare.setTitleUrl(url);
                        paramsToShare.setTitle(getString(R.string.app_name));
                    }
                });
                // 启动分享GUI
                oks.show(this);
                break;
            case R.id.tv_shop_project:
                tvShopProject.setSelected(true);
                tvShopProduct.setSelected(false);
                type = "1";
                mPresenter.getFirstShopType(store_id, type);
                break;
            case R.id.tv_shop_product:
                tvShopProject.setSelected(false);
                tvShopProduct.setSelected(true);
                type = "2";
                mPresenter.getFirstShopType(store_id, type);
                break;
            case R.id.iv_call:
                if (phone != null) {
                    ContactUsDialogFragment dialogFragment = ContactUsDialogFragment.newInstance(phone);
                    dialogFragment.show(getFragmentManager(), "ContactUsDialogFragment");
                }
                break;
            case R.id.iv_shop_location:
                startActivity(ShopMapActivity.createIntent(this, Double.parseDouble(lat),
                        Double.parseDouble(lng), tvShopName.getText().toString(), tvShopAddress.getText().toString()));
                break;
        }
    }

    @Override
    public void setFirstLevel(List<ShopTypeBean.TypeBean> data) {
        firstTypeList = data;
        secondTypeId = firstTypeList.get(0).getId();
        shopNextFirstAdapter.setDatas(data);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setDetailInfo(ShopDetailBean data) {
        imgFavorite.setSelected(!data.getRf_num().equals("0"));
        lat = data.getLat();
        lng = data.getLng();
        tvShopName.setText(data.getName());
        tvShopAddress.setText(data.getProvince() + data.getCity() + data.getArea() + data.getAddresser());
        goodStar.setStarMark(Float.parseFloat(data.getScore()));
        tvGoodScore.setText(String.format(ResourcesUtils.getString(R.string.good_score), data.getScore()));
        tvGoodEvaluation.setText(String.format(ResourcesUtils.getString(R.string.good_evaluation), data.getCount()));
        phone = data.getPhone();

        List<String> imgList = new ArrayList<>();
        String[] split = data.getPic().split(",");
        for (String aSplit : split) {
            imgList.add(RetrofitSource.image_url + aSplit);
        }
        shopBanner.setImages(imgList);
        shopBanner.start();
    }

    @Override
    public void collectSuccess() {
        imgFavorite.setSelected(true);
    }

    @Override
    public void cancelCollectSuccess() {
        imgFavorite.setSelected(false);
    }

    @Override
    public void setProjectSecondLevel(ShopDetailProjectBean data) {
        List<ShopDetailProjectBean.ProjectBean> list = data.getProject();
        if (pageRecorder.getCurrentPage() == 1) {
            shopProjectSecondAdapter.setDatas(list);
        } else {
            shopProjectSecondAdapter.addDatas(list);
        }
        smartRefresh.finishLoadmore();
        pageRecorder.moveToNextPage();
        rvSecondLevel.setAdapter(shopProjectSecondAdapter);
        shopProjectSecondAdapter.setmOnItemClickListener((adapter, position) ->
                startActivity(HotProjectDetailActivity.createIntent(this,
                        shopProjectSecondAdapter.getDatas().get(position).getId())));
    }

    @Override
    public void setProductSecondLevel(List<ShopDetailProductBean> list) {
        if (pageRecorder.getCurrentPage() == 1) {
            shopProductSecondAdapter.setDatas(list);
        } else {
            shopProductSecondAdapter.addDatas(list);
        }
        smartRefresh.finishLoadmore();
        pageRecorder.moveToNextPage();
        rvSecondLevel.setAdapter(shopProductSecondAdapter);
        shopProductSecondAdapter.setmOnItemClickListener((adapter, position) ->
                startActivity(GoodDetailActivity.createIntent(this,
                        shopProductSecondAdapter.getDatas().get(position).getId(),
                        store_id)));
    }
}
